<template>
  <el-card class="box-card">
    <!-- 顶部编辑区 -->
    <div class="header" style="display:flex; justify-content: space-between; align-items: center;">
      <span style="font-size: 16px; font-weight: bold;">基础信息</span>
      <div>
        <el-button v-if="!isEdit" type="primary" size="small" @click="onEdit">编辑</el-button>
        <template v-else>
          <el-button type="success" size="small" @click="onSave">保存</el-button>
          <el-button size="small" @click="onCancel">取消</el-button>
        </template>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="!isEdit"
      style="margin-top: 20px;"
    >
      <!-- 区块 1：基础信息 -->
      <el-card shadow="never" style="margin-bottom: 20px;">
        <template #header>基础信息</template>
        <el-row :gutter="20">
          <template v-if="isPerson">
            <el-col :span="8">
              <el-form-item label="客户编码" prop="code">
                <el-input v-model="form.code" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="姓名" prop="personName">
                <el-input v-model="form.personName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="助记词" prop="personMnemonicWord">
                <el-input v-model="form.personMnemonicWord" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="personSex">
                <el-select v-model="form.personSex" placeholder="请选择">
                  <el-option label="男" value="1" />
                  <el-option label="女" value="2" />
                  <el-option label="未知" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8"><el-form-item label="邮箱" prop="personEmail"><el-input v-model="form.personEmail" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="座机" prop="personLandline"><el-input v-model="form.personLandline" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="手机" prop="personPhone"><el-input v-model="form.personPhone" /></el-form-item></el-col>
            <!-- ... 可继续加 social fields（Facebook/Ins/TikTok/...） -->
          </template>
          <template v-else>
            <el-col :span="8"><el-form-item label="公司名称" prop="companyName"><el-input v-model="form.companyName" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="公司简称" prop="companyAbbrevia"><el-input v-model="form.companyAbbrevia" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="经营范围" prop="companyRange"><el-input v-model="form.companyRange" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="公司规模" prop="companyScale"><el-input v-model="form.companyScale" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="公司电话" prop="companyPhone"><el-input v-model="form.companyPhone" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="公司网址" prop="companyWebsite"><el-input v-model="form.companyWebsite" /></el-form-item></el-col>
            <!-- ... 更多公司字段 -->
          </template>
        </el-row>
      </el-card>

      <!-- 区块 2：分类信息 -->
      <el-card shadow="never" style="margin-bottom: 20px;">
        <template #header>分类信息</template>
        <el-row :gutter="20">
          <el-col :span="8"><el-form-item label="客户来源" prop="sourceCode">
            <el-select v-model="form.sourceCode" placeholder="请选择">
              <el-option v-for="item in dict.source" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="8"><el-form-item label="行业分类" prop="industryCode">
            <el-select v-model="form.industryCode" placeholder="请选择">
              <el-option v-for="item in dict.industry" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="8"><el-form-item label="优先级" prop="priorityCode">
            <el-select v-model="form.priorityCode" placeholder="请选择">
              <el-option v-for="item in dict.priority" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="8"><el-form-item label="星级" prop="starCode">
            <el-select v-model="form.starCode" placeholder="请选择">
              <el-option v-for="item in dict.star" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="8"><el-form-item label="阶段" prop="stageCode">
            <el-select v-model="form.stageCode" placeholder="请选择">
              <el-option v-for="item in dict.stage" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="8"><el-form-item label="状态" prop="statusCode">
            <el-select v-model="form.statusCode" placeholder="请选择">
              <el-option v-for="item in dict.status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
        </el-row>
      </el-card>

      <!-- 区块 3：联系人 -->
      <el-card shadow="never" style="margin-bottom: 20px;">
        <template #header>联系人</template>
        <div style="margin-bottom: 10px;">
          <el-button type="primary" size="small" @click="onContactAdd">新增</el-button>
          <el-button :disabled="!hasSelection" size="small" @click="onContactEdit">编辑</el-button>
          <el-button :disabled="!hasSelection" type="danger" size="small" @click="onContactDelete">删除</el-button>
        </div>
        <el-table
          :data="contacts"
          @selection-change="sel => selected = sel"
          style="width: 100%"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="sex" label="性别" />
          <el-table-column prop="position" label="职务" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="landline" label="座机" />
          <el-table-column prop="phone" label="移动电话" />
          <!-- 其余社交字段略 -->
        </el-table>
      </el-card>

      <!-- 区块 4：其他信息 -->
      <el-card shadow="never">
        <template #header>其他信息</template>
        <el-row :gutter="20">
          <el-col :span="8"><el-form-item label="创建人"><el-input v-model="form.creator" disabled /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="创建时间"><el-input v-model="form.createTime" disabled /></el-form-item></el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 联系人新增/编辑弹窗 -->
    <el-dialog :title="contactDialogTitle" :visible.sync="contactDialogVisible">
      <el-form ref="contactForm" :model="contactForm" label-width="100px">
        <el-form-item label="姓名" prop="name"><el-input v-model="contactForm.name" /></el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="contactForm.sex"><el-option label="男" value="男" /><el-option label="女" value="女" /></el-select>
        </el-form-item>
        <el-form-item label="职务" prop="position"><el-input v-model="contactForm.position" /></el-form-item>
        <el-form-item label="邮箱" prop="email"><el-input v-model="contactForm.email" /></el-form-item>
        <el-form-item label="座机" prop="landline"><el-input v-model="contactForm.landline" /></el-form-item>
        <el-form-item label="手机" prop="phone"><el-input v-model="contactForm.phone" /></el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="contactDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onContactDialogOk">确定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CustInfoApi } from '@/api/cust-info';
import { CustContactsApi } from '@/api/cust-contacts';

interface FormModel { [key: string]: any }
const props = defineProps<{ custId: number }>();

// 编辑状态
const isEdit = ref(false);
const formRef = ref();

// 原始数据备份（用于取消时回滚）
let originalData: any = {};

// 表单数据
const form = reactive<FormModel>({
  typeCode: '', // 'person'|'company'
  // person fields...
  code: '', personName: '', personMnemonicWord: '', personSex: '', personEmail: '', personLandline: '', personPhone: '',
  // company fields...
  companyName: '', companyAbbrevia: '', companyRange: '', companyScale: '', companyPhone: '', companyWebsite: '',
  // 分类
  sourceCode: '', industryCode: '', priorityCode: '', starCode: '', stageCode: '', statusCode: '',
  // 其他
  creator: '', createTime: '',
});

// 字典数据
const dict = reactive({
  source: [] as any[], industry: [], priority: [], star: [], stage: [], status: []
});

// 联系人
const contacts = ref<any[]>([]);
const selected = ref<any[]>([]);
const hasSelection = computed(() => selected.value.length > 0);

// 联系人弹窗
const contactDialogVisible = ref(false);
const contactDialogTitle = ref('新增联系人');
const contactForm = reactive<any>({ id: 0, custId: 0, name: '', sex: '男', position: '', email: '', landline: '', phone: '' });
const contactFormRef = ref();

// 是否个人
const isPerson = computed(() => form.typeCode === 'person');

// 加载字典
async function loadDict() {
  dict.source = (await CustInfoApi.getSourceCode()).data || [];
  dict.industry = (await CustInfoApi.getIndustryCode()).data || [];
  dict.priority = (await CustInfoApi.getPriorityCode()).data || [];
  dict.star = (await CustInfoApi.getStarCode()).data || [];
  dict.stage = (await CustInfoApi.getStageCode()).data || [];
  dict.status = (await CustInfoApi.getStatusCode()).data || [];
}

// 加载客户详情 & 联系人
async function loadData() {
  const res = await CustInfoApi.getCustInfo(props.custId);
  Object.assign(form, res.data);
  form.typeCode = res.data.typeCode;
  originalData = JSON.parse(JSON.stringify(form));
  contacts.value = (await CustContactsApi.listByCustId(props.custId)).data || [];
}

onMounted(async () => {
  await loadDict();
  await loadData();
});

// 编辑/取消/保存
function onEdit() { isEdit.value = true; }
function onCancel() {
  Object.assign(form, originalData);
  isEdit.value = false;
}
async function onSave() {
  try {
    await formRef.value.validate();
    await CustInfoApi.updateCustInfo(form);
    ElMessage.success('保存成功');
    isEdit.value = false;
    originalData = JSON.parse(JSON.stringify(form));
  } catch (err) {
    // 验证或接口错误
  }
}

// 联系人操作
function onContactAdd() {
  Object.assign(contactForm, { id:0, custId: props.custId, name:'', sex:'男', position:'', email:'', landline:'', phone:'' });
  contactDialogTitle.value = '新增联系人';
  contactDialogVisible.value = true;
}
function onContactEdit() {
  const row = selected.value[0];
  Object.assign(contactForm, row);
  contactDialogTitle.value = '编辑联系人';
  contactDialogVisible.value = true;
}
async function onContactDelete() {
  await ElMessageBox.confirm('确认删除所选联系人？', '提示');
  for (const row of selected.value) {
    await CustContactsApi.deleteCustContacts(row.id);
  }
  ElMessage.success('删除成功');
  await loadData();
}
async function onContactDialogOk() {
  await contactFormRef.value.validate();
  if (contactForm.id) {
    await CustContactsApi.updateCustContacts(contactForm);
  } else {
    await CustContactsApi.createCustContacts(contactForm);
  }
  contactDialogVisible.value = false;
  await loadData();
}
</script>

<style scoped>
.box-card { padding: 20px; }
.header .el-button + .el-button { margin-left: 8px; }
</style>
